package com.esincrunch.sms;

import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;

public class reader {
	public Uri SMS_INBOX = Uri.parse("content://sms/inbox");
	public Uri SMS_ALL = Uri.parse("content://sms/");
	private ArrayList<SMSItem> mSmsList = new ArrayList<SMSItem>();
	
	public reader() {
		
	}
	
	public SMSItem get(int idx) {
		return mSmsList.get(idx);
	}
	
	int count() {
		return mSmsList.size();
	}
	
	public int read(Activity activity) {
		Cursor cur = activity.managedQuery(SMS_INBOX, null, null, null, null);
		if( cur != null && 
			cur.moveToFirst()) {
			SMSItem.initIdx(cur);
			do {
				SMSItem item = new SMSItem(cur);
				mSmsList.add(item);
			} while(cur.moveToNext());
		}
		return count();
	}
	
	public void delete(String iid,ContentResolver cr ) {
		Uri mUri=Uri.parse(SMS_ALL + iid);
		cr.delete(mUri, null, null);
	}
	
	public ContactItem getContact(Activity activity, final SMSItem sms) {
		if(sms.mPerson == 0) return null;
		Cursor cur = activity.managedQuery(ContactsContract.Contacts.CONTENT_URI, 
				new String[] {PhoneLookup.DISPLAY_NAME}, 
				" _id=?", 
				new String[] {String.valueOf(sms.mPerson)}, null);
		if(cur != null &&
			cur.moveToFirst()) {
			int idx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);
			ContactItem item = new ContactItem();
			item.mName = cur.getString(idx);
			return item;
		}
		return null;
	}

}
